package com.zhangxin.aiInterview.controller;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.json.JSONUtil;
import com.zhangxin.aiInterview.annotation.AuthCheck;
import com.zhangxin.aiInterview.common.BaseResponse;
import com.zhangxin.aiInterview.common.ErrorCode;
import com.zhangxin.aiInterview.common.ResultUtils;
import com.zhangxin.aiInterview.constant.UserConstant;
import com.zhangxin.aiInterview.exception.BusinessException;
import com.zhangxin.aiInterview.manager.work_flow.ai_hr_interviewer.api.ClearHrConversationContext;
import com.zhangxin.aiInterview.manager.disruptor.WsEventProducer;
import com.zhangxin.aiInterview.model.dto.interview.*;
import com.zhangxin.aiInterview.model.entity.*;
import com.zhangxin.aiInterview.model.enums.AnalyzeStatusEnum;
import com.zhangxin.aiInterview.model.enums.InterviewTypeEnum;
import com.zhangxin.aiInterview.model.enums.IsFullInterviewEnum;
import com.zhangxin.aiInterview.service.*;
import com.zhangxin.aiInterview.utils.BodyActionManager;
import com.zhangxin.aiInterview.utils.FaceActionManager;
import com.zhangxin.aiInterview.utils.FaceEmotionManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 技术面试模块
 */
@RestController
@RequestMapping("/hr/interview")
@Slf4j
public class HrInterviewController {
    @Resource
    private UserService userService;
    //消息生产者
    @Resource
    private WsEventProducer wsEventProducer;
    @Resource
    private PositionService positionService;
    @Resource
    private HrInterviewService hrInterviewService;
    @Resource
    private HrInterviewContentService hrInterviewContentService;
    @Resource
    private ClearHrConversationContext clearHrConversationContext;
    @Resource
    private CozeConversationSessionService cozeConversationSessionService;
    @Resource
    private FaceActionManager faceActionManager;
    @Resource
    private BodyActionManager bodyActionManager;
    @Resource
    private FaceEmotionManager faceEmotionManager;
    @Resource
    private HrInterviewAnalyzeResultService hrInterviewAnalyzeResultService;

    /**
     * 批量查询用户HR面试记录
     * @param request
     * @return
     */
    @GetMapping("/get/user/hrInterview")
    @AuthCheck(mustRole = UserConstant.DEFAULT_ROLE)
    public BaseResponse<List<HrInterview>> getHrInterviewList(HttpServletRequest request){
        Long userId = userService.getLoginUser(request).getId();
        List<HrInterview> hrInterviewList = hrInterviewService.lambdaQuery()
                .eq(HrInterview::getUserId, userId)
                .eq(HrInterview::getIsFull, IsFullInterviewEnum.IS_NOT_FULL_INTERVIEW.getValue())
                .orderByDesc(HrInterview::getCreateTime)
                .list();
        return ResultUtils.success(hrInterviewList);
    }

    /**
     * Hr实时语音面试接口
     * @param userAnswer
     * @param gender
     * @param request
     */
    @GetMapping("/audio")
    @AuthCheck(mustRole = UserConstant.DEFAULT_ROLE)
    public void audioHrInterview(@RequestParam(value = "userContent") String userAnswer, @RequestParam(value = "gender") String gender, HttpServletRequest request) {
        Long userId = userService.getLoginUser(request).getId();
        //获取用户id
        Integer interviewType = userService.getInterviewType(request);
        wsEventProducer.publishEvent(userId, userAnswer, gender, interviewType);
    }

    /**
     * 生成HR面试记录
     *
     * @param interviewGenerateRequest
     * @param request
     * @return
     */
    @PostMapping("/generate")
    public BaseResponse<Long> generateHrInterview(@RequestBody InterviewGenerateRequest interviewGenerateRequest, HttpServletRequest request) {
        Long userId = userService.getLoginUser(request).getId();
        Position position = positionService.getById(interviewGenerateRequest.getPositionId());
        String positionName = position.getName();
        String techFieldName = position.getTechFieldName();
        Long companyId = interviewGenerateRequest.getCompanyId();
        String interviewerGender = interviewGenerateRequest.getInterviewerGender();
        String interviewerType = interviewGenerateRequest.getInterviewerType();
        String languageMode = interviewGenerateRequest.getLanguageMode();
        Long resumeId = interviewGenerateRequest.getResumeId();

        Long hrInterviewId = hrInterviewService.generateHrInterview(userId, position, positionName, techFieldName, companyId, resumeId, interviewerGender, languageMode, interviewerType, false, null);
        return  ResultUtils.success(hrInterviewId);
    }

    /**
     * hr面试分析
     *
     * @param analyzeHrInterviewRequest
     * @return
     */
    @PostMapping("/analyze")
    public BaseResponse<Boolean> analyzeHrInterview(@RequestBody AnalyzeHrInterviewRequest analyzeHrInterviewRequest, HttpServletRequest request) {
        Long fullInterviewId = analyzeHrInterviewRequest.getFullInterviewId();
        Boolean isFull = analyzeHrInterviewRequest.getIsFull();
        //分析hr面
        hrInterviewService.analyzeHrInterview(analyzeHrInterviewRequest, request, isFull, fullInterviewId);
        return ResultUtils.success(true);
    }

    @GetMapping("/cancel")
    public BaseResponse<Boolean> cancelHrInterview(@RequestParam(value = "hrInterviewId") Long hrInterviewId,HttpServletRequest request) {
        boolean update = hrInterviewService.lambdaUpdate()
                .eq(HrInterview::getId, hrInterviewId)
                .set(HrInterview::getInterviewStatus, AnalyzeStatusEnum.UNFINISHED.getValue())
                .update();
        if (!update) throw new BusinessException(ErrorCode.OPERATION_ERROR, "取消面试失败");

        //删除面试内容
        boolean delete = hrInterviewContentService.lambdaUpdate()
                .eq(HrInterviewContent::getHrInterviewId, hrInterviewId)
                .remove();
        if (!delete) throw new BusinessException(ErrorCode.OPERATION_ERROR, "删除面试内容失败");

        Long userId = userService.getLoginUser(request).getId();

        CozeConversationSession conversation = cozeConversationSessionService.lambdaQuery()
                .eq(CozeConversationSession::getUserId, userId)
                .eq(CozeConversationSession::getInterviewType,  InterviewTypeEnum.HR_INTERVIEW.getValue())
                .one();
        //清除面试会话上下文
        if(ObjUtil.isNotEmpty(conversation)){
            clearHrConversationContext.clear(conversation.getConversationId().toString());
        }
        return ResultUtils.success(true);
    }

    /**
     * 获取面部表情
     * @param emotion
     * @param request
     */
    /**
     * 获取面部表情
     * @param getFaceEmotionRequest
     * @param request
     */
    @PostMapping("/face/emotion")
    public void getHrFaceEmotion(@RequestBody GetFaceEmotionRequest getFaceEmotionRequest, HttpServletRequest request){
        Long userId = userService.getLoginUser(request).getId();
        List<String> faceEmotions = getFaceEmotionRequest.getFaceEmotions();
        StringBuilder sb = new StringBuilder();
        if(!faceEmotions.isEmpty()){
            sb.append(faceEmotions.get(0));
            for(int i=1; i<faceEmotions.size(); i++){
                sb.append("//").append(faceEmotions.get(i));
            }
            faceEmotionManager.addEmotion(userId, sb.toString());
            List<String> faceEmotionStorageEmotions = faceEmotionManager.getEmotions(userId);
            System.out.println(JSONUtil.toJsonStr(faceEmotionStorageEmotions));
        }
    }

    /**
     * 获取面部动作
     */
    @PostMapping("/face/action")
    public void getHrFaceAction(@RequestBody GetFaceActionRequest getFaceActionRequest, HttpServletRequest request){
        // 1. 获取当前用户ID
        Long userId = userService.getLoginUser(request).getId();

        // 2. 从请求中提取动作数据
        List<GetFaceActionRequest.FaceAction> requestActions = getFaceActionRequest.getFaceActionList();

        // 3. 初始化动作计数器
        String eyeBlink = "0";
        String mouthPuff = "0";
        String eyeUpLeft = "0";
        String eyeUpRight = "0";

        // 4. 遍历请求数据并分类存储
        for (GetFaceActionRequest.FaceAction action : requestActions) {
            switch (action.getFaceAction()) {
                case "EYE_BLINK":
                    eyeBlink = action.getCounter().toString();
                    break;
                case "MOUTH_PUFF":
                    mouthPuff = action.getCounter().toString();
                    break;
                case "EYE_UP_LEFT":
                    eyeUpLeft = action.getCounter().toString();
                    break;
                case "EYE_UP_RIGHT":
                    eyeUpRight = action.getCounter().toString();
                    break;
            }
        }

        // 5. 封装为FaceAction对象
        FaceActionManager.FaceAction faceAction = new FaceActionManager.FaceAction(
                eyeBlink, mouthPuff, eyeUpLeft, eyeUpRight
        );

        // 6. 存储到Manager
        faceActionManager.addFaceAction(userId, faceAction);
    }

    /**
     * 获取身体动作
     */
    @PostMapping("/body/action")
    public void getHrBodyAction(@RequestBody GetBodyActionRequest getBodyActionRequest, HttpServletRequest request){
        // 1. 获取当前用户ID
        Long userId = userService.getLoginUser(request).getId();

        // 2. 从请求中提取动作数据
        List<GetBodyActionRequest.BodyAction> requestActions = getBodyActionRequest.getBodyActionList();

        // 3. 初始化动作计数器
        String earTouch = "0";
        String noseTouch = "0";

        // 4. 遍历请求数据并分类存储
        for (GetBodyActionRequest.BodyAction action : requestActions) {
            switch (action.getBodyAction()) {
                case "ear":
                    earTouch = action.getCounter().toString();
                    break;
                case "nose":
                    noseTouch = action.getCounter().toString();
                    break;
            }
        }

        // 5. 封装为BodyAction对象
        BodyActionManager.BodyAction bodyAction = new BodyActionManager.BodyAction(
                earTouch, noseTouch
        );

        // 6. 存储到Manager
        bodyActionManager.addBodyAction(userId, bodyAction);
    }

    /**
     * 获取分析结果
     * @param hrInterviewId
     * @return
     */
    @GetMapping("/get/analyzeResult")
    public BaseResponse<HrInterviewAnalyzeResult> getHrInterviewAnalyzeResult(@RequestParam("hrInterviewId") Long hrInterviewId){
        HrInterviewAnalyzeResult hrInterviewAnalyzeResult = hrInterviewAnalyzeResultService.lambdaQuery()
                .eq(HrInterviewAnalyzeResult::getHrInterviewId, hrInterviewId)
                .one();
        return ResultUtils.success(hrInterviewAnalyzeResult);
    }

    /**
     * 删除HR面试记录
     * @param hrInterviewId
     * @param request
     * @return
     */
    @GetMapping("/delete")
    @AuthCheck(mustRole = UserConstant.DEFAULT_ROLE)
    public BaseResponse<Boolean> deleteHrInterview(@RequestParam(value = "hrInterviewId") Long hrInterviewId, HttpServletRequest request) {
        boolean b = hrInterviewService.deleteHrInterview(hrInterviewId, request);
        return ResultUtils.success(b);
    }
}